import { Tabs, List, Card, Image, Grid, Toast } from 'react-vant';
import './Home.css';
import { useState, useEffect } from 'react';
import goodApi from '@/apis/goodApi';
import { debounceAsync, getGoodsImagePath, getSaleCount } from '@/utils/common';
import { ArrowUp } from '@react-vant/icons';
import { useNavigate } from 'react-router-dom';
import MyPromotePrice from '@/components/MyPromotePrice';

const Home: React.FC = () => {
  const [categories, setCategories] = useState([
    { id: -1, name: '热销' },
    { id: -2, name: '折扣' },
  ]);
  const [activeCategory, setActiveCategory] = useState(0);
  const [finished, setFinished] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [goodsData, setGoodsData] = useState<ResponseGoodList[]>([]);
  const [showBackTop, setShowBackTop] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const handleScroll = () => {
      const scrollY = window.scrollY || document.documentElement.scrollTop;
      setShowBackTop(scrollY > 200);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  useEffect(() => {
    const fetchData = async () => {
      const res = await goodApi.getGoodType();
      setCategories((prev) => [
        ...prev,
        ...res.data.map((d: any) => {
          return { id: d.gtid, name: d.gtName };
        }),
      ]);
    };
    fetchData();
  }, []);

  const onLoadMore = async () => {
    try {
      const limit = 10;
      let res: ResponseApiDto;
      if (activeCategory === 0) {
        res = await goodApi.getGoodHot(currentPage, limit);
      } else if (activeCategory === 1) {
        res = await goodApi.getGoodPromote(currentPage, limit);
      } else {
        res = await goodApi.getGoodPagnation(currentPage, limit, categories[activeCategory].id);
      }
      setGoodsData((prev) => [...prev, ...res.data.data]);
      setCurrentPage((prev) => prev + 1);
      setFinished(goodsData.length + limit >= res.data.total);
    } catch (error) {
      Toast.fail('加载失败');
    }
  };

  const resetPagination = () => {
    setGoodsData(() => []);
    setCurrentPage(1);
    setFinished(false);
  };

  const handleProductClick = (id: number) => {
    navigate('/good/' + id);
  };

  return (
    <div className="home-page">
      <Tabs
        active={activeCategory}
        onChange={debounceAsync((_: any, tabIndex: number) => {
          setActiveCategory(tabIndex);
          resetPagination();
        }, 100)}
        swipeable
      >
        {categories.map((cat) => (
          <Tabs.TabPane key={cat.id} title={cat.name}></Tabs.TabPane>
        ))}
      </Tabs>
      <List finished={finished} errorText="请求失败，点击重新加载" onLoad={onLoadMore}>
        <Grid columnNum={2} border={false}>
          {goodsData.map((item) => (
            <Grid.Item key={item.id}>
              <Card className="product-card" onClick={() => handleProductClick(item.id)}>
                <div className="image-box">
                  <Image
                    src={getGoodsImagePath(item.id, item.photo)}
                    alt={item.name}
                    width="100%"
                    height="160"
                  />
                </div>
                <div className="product-info">
                  <h3>{item.name}</h3>
                  <div className="spec-section">{item.spec}</div>
                  <div className="price-section">
                    <MyPromotePrice price={item.price} propmotePrice={item.promotePrice} />
                  </div>
                  <div className="sales">已售{getSaleCount(item.saleCout)}份</div>
                </div>
              </Card>
            </Grid.Item>
          ))}
        </Grid>
        {finished ? <div className="no-more-text">没有更多了</div> : null}
      </List>
      {/* 在列表后添加返回顶部按钮 */}
      {showBackTop && (
        <div className="back-to-top" onClick={scrollToTop}>
          <ArrowUp />
        </div>
      )}
    </div>
  );
};

export default Home;
